<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
  </head>

  <body>
    <script>
      //请求某个图片资源
      function requestImg() {
        var p = new Promise(function (resolve, reject) {
          var img = new Image();
          img.onload = function () {
            resolve(img);
          };
          img.src = 'images/1.jpg';
        });
        return p;
      }

      //延时函数，用于给请求计时
      function timeout() {
        var p = new Promise(function (resolve, reject) {
          setTimeout(function () {
            reject('图片请求超时');
          }, 200);
        });
        return p;
      }

      //Promise的静态方法 race
      Promise.race([requestImg(), timeout()])
        .then(function (results) {
          console.log('成功');
          console.log(results);
          document.body.appendChild(results);
        })
        .catch(function (reason) {
          console.log('失败');
          console.log(reason);
        });
    </script>
  </body>
</html>
